package com.intelligentmeterreadingsys.waterbanding.activity;

import java.util.Date;

import android.app.ActivityGroup;
import android.app.AlertDialog.Builder;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.location.LocationManager;
import android.os.Bundle;
import android.provider.Settings;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RadioGroup.OnCheckedChangeListener;
import android.widget.Toast;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.intelligentmeterreadingsys.R;
import com.intelligentmeterreadingsys.povo.UserWaterVO;
import com.intelligentmeterreadingsys.util.SharedPreferenceUtil;
import com.intelligentmeterreadingsys.util.TipHelper;

import dbhelper.XmlNameHelper;

/**
 * 绑定水表FIND卡,主界面
 * 
 * @author king
 * 
 */
public class WaterBandingMainActivity extends ActivityGroup implements
		BDLocationListener {
	private LinearLayout container = null;
	private RadioGroup radiogroup = null;
	private RadioButton radio1 = null;
	private RadioButton radio3 = null;
	private final static int DIALOG = 1;
	private String waterid;
	public String locationtype = "gps";
	public SharedPreferenceUtil sp;

	public String getWaterid() {
		return waterid;
	}

	public void setWaterid(String waterid) {
		this.waterid = waterid;
	}

	public long time;

	public LocationClient client;// 定位对象

	public ProgressDialog pd;

	public WaterBandingActivity act;

	@Override
	protected void onCreate(Bundle savedInstanceState) {

		super.onCreate(savedInstanceState);
		setContentView(R.layout.waterbanding_main_layout);

		waterid = getIntent().getStringExtra("waterid");

		waterid = getIntent().getExtras().getString("waterid");
		System.out.println(waterid + "----------waterid");
		pd = new ProgressDialog(this);
		sp = new SharedPreferenceUtil(this);
		init();

	}

	/**
	 * 界面切换
	 * 
	 * @param id
	 * @param activityClass
	 */
	public void launchActivity(String id, Class<?> activityClass, Bundle bundle) {
		container.removeAllViews();

		Intent intent = new Intent(WaterBandingMainActivity.this, activityClass);
		if (bundle != null) {
			intent.putExtras(bundle);
		}
		intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);

		Window window = getLocalActivityManager().startActivity(id, intent);
		View view = window.getDecorView();
		container.addView(view);
	}

	/**
	 * 初始化控件
	 */
	public void init() {

		container = (LinearLayout) findViewById(R.id.waterbanding_linear);
		radiogroup = (RadioGroup) findViewById(R.id.waterbanding_radiogroup);
		radio1 = (RadioButton) findViewById(R.id.waterbanding_radio_button0);

		radio3 = (RadioButton) findViewById(R.id.waterbanding_radio_button2);

		Bundle bundle = new Bundle();

		bundle.putBoolean("key", true);

		launchActivity("WaterBandingActivity", WaterBandingActivity.class,
				bundle);
		radio1.setChecked(true);
		act = (WaterBandingActivity) getCurrentActivity();
		Button button = null;
		button.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {

				UserWaterVO user = act.list;

				if (user == null || act.RFID == null || act.RFID.equals("")) {
					Toast.makeText(WaterBandingMainActivity.this,
							"定位前请读卡，保证有水表，且你在此水表位置", 1000).show();
					return;
				}
				boolean b = openGPSSettings();
				if (b) {
					initlocation();
					time = System.currentTimeMillis();
					pd.setMessage("定位中.....");
					pd.show();
					client.start();
				}

			}
		});
		radiogroup.setOnCheckedChangeListener(new OnCheckedChangeListener() {

			@Override
			public void onCheckedChanged(RadioGroup group, int checkedId) {
				if (checkedId == radio1.getId()) {

					launchActivity("WaterBandingActivity",
							WaterBandingActivity.class, null);
					act = (WaterBandingActivity) getCurrentActivity();

					UserWaterVO user = act.list;

					initlocation();
					if (user == null || act.RFID == null || act.RFID.equals("")) {
						Toast.makeText(WaterBandingMainActivity.this,
								"定位前请读卡，保证有水表，且你在此水表位置", 1000).show();
						return;
					}
					Button button = null;
					button.setOnClickListener(new OnClickListener() {

						@Override
						public void onClick(View v) {
							boolean b = openGPSSettings();
							if (b) {
								time = System.currentTimeMillis();
								pd.setMessage("定位中.....");
								pd.show();
								client.start();
							}
						}
					});
				} else if (checkedId == radio3.getId()) {
					launchActivity("WaterBandingUploadActivity",
							WaterBandingUploadActivity.class, null);
				}

			}
		});

	}

	/**
	 * 打开子Activity的菜单事件
	 */
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_MENU) {
			getCurrentActivity().openOptionsMenu();
		} else if (keyCode == KeyEvent.KEYCODE_BACK) {

		}
		return super.onKeyDown(keyCode, event);
	}

	@Override
	public void onReceiveLocation(BDLocation location) {

		GPS(location);

	}

	@Override
	public void onReceivePoi(BDLocation arg0) {

	}

	/**
	 * 得到定位数据
	 * 
	 * @param location
	 */
	public void GPS(BDLocation location) {

		if (location != null) {
			if (locationtype.equals("gps")) {
				if (location.getLocType() == 161) {
					client.stop();
					pd.setMessage("定位成功");
					act.textview6.setText("纬度:" + location.getLatitude());
					act.textview7.setText("经度：" + location.getLongitude());
					act.latitude = location.getLatitude();
					act.longitude = location.getLongitude();

					Toast.makeText(WaterBandingMainActivity.this,
							"定位成功" + location.getLocType(), Toast.LENGTH_LONG)
							.show();
					TipHelper.Vibrate(WaterBandingMainActivity.this, 1000);
					pd.dismiss();
					sp.insertValue(XmlNameHelper.GPSLATITUDE,
							location.getLatitude() + "");
					sp.insertValue(XmlNameHelper.GPSLONGITUDE,
							location.getLongitude() + "");
					sp.insertValue(XmlNameHelper.GPSDATE,
							System.currentTimeMillis() + "");
					client.registerLocationListener(this);
				}
			}
		}
		Date d = new Date();

		if (d.getTime() - time > 60000) {
			client.stop();
			client.registerLocationListener(this);
			pd.setMessage("定位超时...");

			Toast.makeText(WaterBandingMainActivity.this, "定位超时",
					Toast.LENGTH_LONG).show();
			TipHelper.Vibrate(WaterBandingMainActivity.this, 1000);

			pd.dismiss();
			showDialog(DIALOG);

		}
	}

	/**
	 * 初始化定位
	 */
	public void initlocation() {
		if (client != null) {
			client.stop();
		}
		client = new LocationClient(this);
		LocationClientOption option = new LocationClientOption();
		// 打开GPS
		option.setOpenGps(true);

		// 设置坐标类型
		option.setCoorType("bd09ll");

		// 设置网络优先
		if (locationtype.equals("gps")) {

			option.setPriority(LocationClientOption.GpsFirst);
		}

		// 设置产品线名称
		option.setProdName("waterSys");
		option.disableCache(true);// 禁止启用缓存定位
		// 设置定位定时时间
		option.setScanSpan(10000);
		client.setLocOption(option);
		client.registerLocationListener(this);

	}

	@Override
	protected Dialog onCreateDialog(int id) {
		Dialog dialog = null;
		switch (id) {
		case DIALOG:

			Builder builder = new android.app.AlertDialog.Builder(this);
			// 设置对话框的图标
			builder.setIcon(R.drawable.buttondraw);

			// 设置对话框的标题
			builder.setMessage("最近一次定位时间在:"
					+ sp.getValue(XmlNameHelper.GPSDATE));
			// 0: 默认第一个单选按钮被选中

			// 添加一个确定按钮
			builder.setPositiveButton(" 确 定 ",
					new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog, int which) {
							act.textview6.setText("径度"
									+ sp.getValue(XmlNameHelper.GPSLONGITUDE));
							act.textview7.setText("维度："
									+ sp.getValue(XmlNameHelper.GPSLATITUDE));
							act.latitude = Double.parseDouble(sp
									.getValue(XmlNameHelper.GPSLATITUDE));
							act.longitude = Double.parseDouble(sp
									.getValue(XmlNameHelper.GPSLONGITUDE));
						}
					});
			builder.setNeutralButton("取消",
					new DialogInterface.OnClickListener() {

						@Override
						public void onClick(DialogInterface dialog, int which) {
							act.textview6.setText("径度:" + 0.0);
							act.textview7.setText("维度：" + 0.0);
							act.latitude = 0.0;
							act.longitude = 0.0;

						}
					});
			// 创建一个单选按钮对话框
			dialog = builder.create();

			break;

		default:
			break;
		}

		return dialog;
	}

	/**
	 * 判断GPS是否存在或开启
	 */
	public boolean openGPSSettings() {
		LocationManager alm = (LocationManager) getSystemService(this.LOCATION_SERVICE);

		if (alm.isProviderEnabled(android.location.LocationManager.GPS_PROVIDER)) {

			return true;
		}
		Toast.makeText(this, "请开启GPS！", Toast.LENGTH_SHORT).show();
		Intent intent = new Intent(Settings.ACTION_SECURITY_SETTINGS);
		startActivityForResult(intent, 0); // 此为设置完成后返回到获取界面
		return false;
	}

}
